from django.template import loader

from apps.contents.utils import get_categories
from apps.goods.models import SKU
from apps.goods.utils import get_breadcrumb
from celery_tasks.main import app
from meiduo_mail import settings

@app.task(name='get_detail_html')
def get_detail_html(sku_id):
    try:
        sku = SKU.objects.get(pk=sku_id)
    except:
        raise Exception('商品无效')
    categories = get_categories()
    breadcrumb = get_breadcrumb(sku.category)
    spu = sku.spu
    specs = spu.specs.order_by('id')
    skus = spu.sku_set.order_by('id')
    sku_options = []
    sku_option = {}
    for s in skus:
        infos = s.specs.order_by('spec_id')
        option_key = []
        for info in infos:
            option_key.append(info.option_id)
            if sku.id == s.id:
                sku_option.append(info.option_id)
            sku_options[tuple(option_key)] = s.id
        specs_list = []
        for index, spec in enumerate(specs):
            option_list = []
            for option in spec.options.all():
                sku_option_temp = sku_option[:]
                sku_option_temp[index] = option.id
                option.sku_id = sku_options.get(tuple(sku_option_temp), 0)
                option_list.append(option)
            spec.option_list = option_list
            specs_list.append(spec)
            context = {
                'sku': sku,
                'categories': categories,
                'breadcrumb': breadcrumb,
                'category_id': sku.category_id,
                'spu': spu,
                'specs': specs_list
            }
            template = loader.get_template('detail.html')
            html_str = template.render(context)
            file_path = settings.STATIC_FILE_PATH + "%s.html" % sku_id
            # print(file_path)
            with open(file_path, 'a', encoding='utf-8') as f:
                f.write(html_str)
